package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.entity.UserLogin;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/getCode")
    public R<String> getCode(@RequestBody User user, HttpServletRequest request) {
        Integer i = ValidateCodeUtils.generateValidateCode(6);
        log.info("手机号：{}，接收到验证码：{}", user.getPhone(), i );

        request.getSession().setAttribute(user.getPhone(), i.toString());
        return R.success(i.toString());
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody UserLogin userLogin, HttpServletRequest request) {
        String code = (String) request.getSession().getAttribute(userLogin.getPhone());
        // 验证码比对
        if (!code.equals(userLogin.getCode())){
            return R.error("验证码错误");
        }
        //查看是否存在此用户
        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, userLogin.getPhone()));
        if (one == null) {
            //不存在，创建新用户
            one = new User();
            one.setPhone(userLogin.getPhone());
            one.setStatus(1);
            userService.save(one);
        }
        request.getSession().setAttribute("user",one.getId());
        return R.success(one,"登录成功");

    }
}
